package com.wjjm.spoonselling.controller;

import com.wjjm.spoonselling.pojo.Commodity;
import com.wjjm.spoonselling.service.CommodityService;
import com.wjjm.spoonselling.util.Code;
import com.wjjm.spoonselling.util.Result;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping
public class CommodityController {

    @Autowired
    private CommodityService commodityService;

    @GetMapping("/selectAll")
    public Result selectAll(){
        List<Commodity> commodities = commodityService.selectAll();
        int code  = commodities != null ? Code.SELECT_OK:Code.SELECT_ERR;
        String msg = commodities != null ? "数据查询成功":"数据查询失败，请重试";
        return new Result(code,commodities,msg);
    }

    @GetMapping("/selectById/{commodityId}")
    public Result selectById(@PathVariable int commodityId){
        Commodity commodity = commodityService.selectById(commodityId);
        int code = commodity != null ? Code.SELECT_OK:Code.SELECT_ERR;
        String msg = commodity != null ? "数据查询成功":"数据查询失败，请重试";
        return new Result(code,commodity,msg);
    }

    @PutMapping("/update")
    public Result update(@RequestBody Commodity commodity){
        boolean flag = commodityService.update(commodity);
        int code = flag == true ? Code.UPDATE_OK:Code.UPDATE_ERR;
        String msg = flag == true ? "数据更新成功":"数据更新失败，请重试";
        return new Result(code,flag,msg);
    }

    @GetMapping("/deleteById/{commodityId}")
    public  Result deleteById(@PathVariable int commodityId){
        boolean flag = commodityService.deleteById(commodityId);
        return new Result(flag? Code.DELETE_OK:Code.DELETE_ERR, flag);
    }

    @PostMapping("/insert")
    public Result insert(@RequestBody Commodity commodity){
        int i = commodityService.insert(commodity);
        int code = i != 0 ? Code.ADD_OK : Code.ADD_ERR;
        String msg = i != 0 ? "数据插入成功":"数据插入失败，请重试";
        return new Result(code,i,msg);
    }

    @GetMapping("/selectByName")
    public Result selectByName(String name){
        if("null".equals(name)){
            List<Commodity> commodities = commodityService.selectAll();
            int code = commodities != null ? Code.SELECT_OK : Code.SELECT_ERR;
            String msg = commodities != null ? "数据查询成功":"数据查询失败,请重试";
            return new Result(code,commodities,msg);
        }else {
            name = "%" + name + "%";
            List<Commodity> commodities = commodityService.selectByName(name);
            int code = commodities != null ? Code.SELECT_OK:Code.SELECT_ERR;
            String msg = commodities != null ? "数据查询成功":"数据查询失败，请重试";
            return new Result(code,commodities,msg);
        }
    }
}
